package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //先判断地址簿是否为空
        AddressBook address = addressMapper.getAddressById(ordersSubmitDTO.getAddressBookId());
        if (address == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询购物车数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCarts = shoppingCartMapper.getGoods(shoppingCart);
        if (shoppingCarts == null) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //往订单表插入数据
//        Orders orders = new Orders();
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(5);//订单的状态 代表已完成
        order.setPayStatus(1);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        orderMapper.insert(order);


        ArrayList<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());//设置订单id
            list.add(orderDetail);
        }
        orderDetailMapper.insertBatch(list);//批量插入
        //清空购物车
        shoppingCartMapper.deleteShopCart();
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount()).build();
        return orderSubmitVO;
    }

    @Override
    public void updateOrderStatus(Integer orderId, Integer status) {
        orderMapper.updateOrderStatus(orderId, status);
    }

    @Override
    public Orders getOrdersById(Integer id) {
        return orderMapper.getOrersById(id);
    }

    @Override
    public BusinessDataVO getNowDate() {
        LocalDate date = LocalDate.now();
        Map map = getMap(date);
        map.put("status", Orders.COMPLETED);

        Double todayTotalMoney = orderMapper.getNowTurnOver(map);//今日营业额
        todayTotalMoney = todayTotalMoney == null ? 0.0 : todayTotalMoney;
        Integer vaildCount = orderMapper.getEveryOrderCount(map);//今天有效订单

        Double unitPrice = 0.0;

        if (todayTotalMoney != null && todayTotalMoney != 0 && vaildCount != null && vaildCount != 0) {
            unitPrice = todayTotalMoney / vaildCount;//客单价
        }

        Map mapTotal = getMap(date);

        Integer nowTotalCount = orderMapper.getEveryOrderCount(mapTotal);//今日订单总数
        Integer nowUserCount = userMapper.newCountByMap(map);//今日新增用户
        Double orderCompletionRate = 0.0;

        if (nowTotalCount != 0 && vaildCount != 0) {
            orderCompletionRate = Double.valueOf(vaildCount) / Double.valueOf(nowTotalCount);
            System.out.println(orderCompletionRate);
        }
        return BusinessDataVO.builder()
                .turnover(todayTotalMoney)
                .validOrderCount(vaildCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(nowUserCount)
                .build();
    }

    @Override
    public OrderOverViewVO getOrederOver() {
        Integer totalOrderCount = orderMapper.getTotalOrderCount();//总订单
        Integer validCount = orderMapper.getValidCount();//已经完成的订单
        System.out.println(validCount);
        Integer waitAccetOrder = orderMapper.getWaitAcceptOrder();//待接单
        Integer waitSendOrder = orderMapper.getWaitSendOrder();//待派送
        Integer alreadyCancelOrder = orderMapper.getAlreadyCancelOrder();//已取消
        return OrderOverViewVO.builder()
                .waitingOrders(waitAccetOrder)
                .deliveredOrders(waitSendOrder)
                .completedOrders(validCount)
                .cancelledOrders(alreadyCancelOrder)
                .allOrders(totalOrderCount)
                .build();
    }

    //获取基本的map集合
    public Map getMap(LocalDate date) {
        LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//获取的是 0：00  当天的开始
        LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//23：59：5999999999 当天的快结束
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return map;
    }
}
